package gui.panels;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import mysql.LocationQueries;
import mysql.PersonQueries;
import objects.Location;
import objects.Person;

public class AddPerson extends JFrame implements ActionListener {
	
	public Person pcurrentEntry;
	public PersonQueries personQueries;
	public List<Person> pResults;
	public int pnumberOfEntries = 0;
	public int pCurrentEntryIndex = 0;
	
	public Location loccurrentEntry;
	public LocationQueries locQueries;
	public List<Location> locResults;
	public int locnumberOfEntries = 0;
	public int locCurrentEntryIndex = 0;
	
	private JLabel firstLabel;
	public JTextField firstText;
	private JLabel lastLabel;
	public JTextField lastText;
	private JLabel locLabel;
	public JTextField locText;
	public JButton add;
	public JButton cancel;
	public JPanel displayPanel;
	public JComboBox locCombo;
	public int nextEntry;
	
	
	public AddPerson() {
		setData();
		getLocations();
		firstLabel = new JLabel("Firstname:");
		firstText = new JTextField(20);
		lastLabel = new JLabel("Lastname:");
		lastText = new JTextField(20);
		locLabel = new JLabel("Location id");
		locText = new JTextField(10);
		displayPanel = new JPanel();
		add = new JButton("Add new user");
		cancel = new JButton("Cancel");
		
		displayPanel.setLayout(new GridLayout(4, 2, 4, 4));
		displayPanel.add(firstLabel);
		displayPanel.add(firstText);
		displayPanel.add(lastLabel);
		displayPanel.add(lastText);
		displayPanel.add(locLabel);
		displayPanel.add(locCombo);
		displayPanel.add(add);
		displayPanel.add(cancel);
		
		add.addActionListener(this);
		cancel.addActionListener(this);
		
		
		add(displayPanel, BorderLayout.CENTER);
		pack();
		setVisible(true);
	}

	private void setData() {
		personQueries = new PersonQueries();
		pResults = personQueries.getAllPeople();
		nextEntry = pResults.get(pResults.size()-1).getPid()+1;
	}
	
	private void getLocations() {
		locQueries = new LocationQueries();
		locResults = locQueries.getAllLocations();
		String[] comboArray = new String[locResults.size()];
		for (int i=0;i<locResults.size();i++) {
			comboArray[i] = locResults.get(i).getAddress();
		}
		locCombo = new JComboBox(comboArray);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		if (arg0.getSource() == this.add) {
			personQueries.addPerson(nextEntry, firstText.getText(), lastText.getText(), locCombo.getSelectedIndex() + 102 );
			super.dispose();
		}
		if (arg0.getSource() == this.cancel) {
			super.dispose();
		}
		
	}

}
